<template>
  <SealAddConfig
    ref="refStep1"
    @submit="
      params => {
        changeCurStep(2, params);
      }
    "
  />
  <Validator
    ref="refStep2"
    @submit="
      params => {
        changeCurStep(3);
      }
    "
  />
  <SealSelector purpose="byWord" ref="refStep3" @submit="doSealAdd" />
</template>
<script setup>
import { reactive, toRefs, ref, inject } from "vue";
import Validator from "../_validator.vue";
import SealSelector from "../_sealSelector.vue";
import SealAddConfig from "./components/ByWordConfig.vue";
import _ from "lodash";
import { seal, ss, ls } from "@/utils";

const provideHome = inject("provideHome");
const refStep1 = ref();
const refStep2 = ref();
const refStep3 = ref();
const state = reactive({
  style: {},
  formData: {
    keyword: "",
  },
});
const { style, formData } = toRefs(state);

const WORD_HISTORY_KEY = "wordHistory";

const changeCurStep = (curStep, params = {}) => {
  _.assign(state.formData, params);
  refStep1.value.close();
  refStep2.value.close();
  refStep3.value.close();
  if (curStep == 1) {
    refStep1.value.show();
  } else if (curStep == 2) {
    refStep2.value.show();
  } else if (curStep == 3) {
    refStep3.value.show();
  }
  setTimeout(() => {
    provideHome.methods.setSealCurrentOperateName("btnSealAddByWord");
  }, 30);
};

const cacheNewWord = () => {
  let { keyword } = state.formData;
  let newCache = ls.get(WORD_HISTORY_KEY) || [];
  newCache.unshift(keyword);

  // 使用 Set 对象去重
  let finalCache = Array.from(new Set(newCache));
  if (finalCache.length > 9) {
    finalCache.length = 9;
  }
  ls.set(WORD_HISTORY_KEY, finalCache);
};

const doSealAdd = async params => {
  let { sealInfo } = params;
  cacheNewWord();
  await seal.doSealAdd({
    fileId: ss.get("fileId"),
    signatureInfo: {
      signatureType: "custom",
      page: 0,
      keyword: state.formData.keyword,
    },
    sealSn: sealInfo.sealSn,
    positionType: 2,
    signContinued: "00",
    sealType: sealInfo.sealType,
  });
};

defineExpose({
  show() {
    changeCurStep(1);
  },
});
</script>
<style lang="scss"></style>
